import Vue from 'vue'
import VueRouter from 'vue-router'
import Utils from './utils.js'
import store from './store.js'
import { Indicator } from 'mint-ui';


Vue.use(VueRouter)

import Game from './views/game.vue'
import StartPage from './views/start.vue'
import shareStart from './views/shareStart.vue'

const routers = [
  {
    path:'',
    component: StartPage
  },
  {
    path: '/shareStart',
    component: shareStart
  },
  {
    path: '/start',
    component: StartPage
  },
  {
    path: '/game',
    component: Game,
    meta:{
      keepAlive:true
    }
  }
]

const router = new VueRouter({
  routes: routers
});



const wxSetConfig = function (data,callback) {
  //微信授权页面sdk
  wx.config({
    debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
    appId: Utils.config().appid, // 必填，公众号的唯一标识
    timestamp: data.timestamp, // 必填，生成签名的时间戳
    nonceStr: data.nonceStr, // 必填，生成签名的随机串
    signature: data.signature, // 必填，签名，见附录1
    jsApiList: ['onMenuShareTimeline', 'onMenuShareAppMessage'] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
  });
  wx.ready(function () {
    wx.onMenuShareTimeline(store.getters.wxShareData)
    wx.onMenuShareAppMessage(store.getters.wxShareData)
    callback && callback()
  })
}



var pageCount = 0

// 只在每次刷新或者重新打开页面时候  初始化用户数据
store.commit('initUser')
router.beforeEach((to,from,next)=>{
  if (window.location.href.indexOf('.html?') > -1) {
    // alert('链接异常')
    // 对异常链接处理
    // 微信分享后http://192.168.1.83:3000/index.html?from=singlemessage#/game?showId=22
    var hrefArr = window.location.href.split('#')
    var str77 = hrefArr[0].split('?')[0] + '#'
    str77 += hrefArr[1]
    if (Utils.getQueries(hrefArr[0]).code) {
      //取出code
      // alert(Utils.getQueries(hrefArr[0]).code)
      if (str77.indexOf('?') > -1) {
        str77 += '&' + 'code=' + Utils.getQueries(hrefArr[0]).code
      } else {
        str77 += '?' + 'code=' + Utils.getQueries(hrefArr[0]).code
      }
    }
    // alert('重新定向:' + str77)
    window.location.href = str77
    return false
  }
  console.log(to)
  if (Utils.getQueries().showId) { //分享id
    store.commit('setShowId', Utils.getQueries().showId)
  }
  pageCount++
  // 判断缓存  是否有用户信息
  var userInfo = store.state.user
  if (!userInfo ){
    var code = Utils.getQueries().code//判断code
    if (code) { 
      // 用微信返回的code，获取用户信息
      Indicator.open({
        text: '微信授权登录中...',
        spinnerType: 'fading-circle'
      });

      store.dispatch('getUserInfo',{code}).then(()=>{ 
        store.dispatch('getWxConfig').then(data=>{
          wxSetConfig(data)
          Indicator.close()
          if (pageCount == 1) {
            store.dispatch('addPvUv')
          }
          if (localStorage.getItem('nianshou_href')) {
            var str8 = localStorage.getItem('nianshou_href')
            console.log('存储链接', str8)
            localStorage.removeItem('nianshou_href')
            Indicator.close()
            if (Utils.getQueries(str8).showId){
                next({
                  path: str8.split('?')[0],
                  query: Utils.getQueries(str8)
                })
            }else{
              next()
            }
          } else {
            next()
          }
          
        })
      })
    }else{
      //先跳转获取授权  明授权  需要用户确认,确认后 跳转到上一步 code
      localStorage.setItem('nianshou_href', window.location.href.split('#')[1]) //缓存跳转微信前的路由信息
      var href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${Utils.config().appid}&redirect_uri=${window.location.href.split('#')[0]}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redire`
      window.location.href = href
      // https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx8fc20b3cc2f7bba8&redirect_uri=http://temporary.birdjia.com/bird_dsp/activity/monsterNian/dist/index.html&connect_redirect=1&uin=NjYwNDA0MDYw&key=3ebd1bfb39007fa6ddc02f8804a6d99d7346bcf72ff6ff26e1e94f4e2d39f97b52a52f40a5b448e8bf75c02101e3680d&pass_ticket=xBwje38slin/498cSgHPAgL6XPjjq7dbkvs7LpJT9Stw2nH8ASnt6x0NBbZOGfYO/ZlGbi6iPYUuI/vRbTYSDg==
      return
    }
  }else{
    if (pageCount == 1) {
       store.dispatch('addPvUv')
    }
    store.dispatch('getWxConfig').then(data=>{
      wxSetConfig(data)
      if (localStorage.getItem('nianshou_href')) {
        var str6 = localStorage.getItem('nianshou_href')
        localStorage.removeItem('nianshou_href')
        // location.hash = str6
        next({
          path: str6.split('?')[0],
          query: Utils.getQueries(str6)
        })
      } else {
        next()
      } 
    }) 
  }  
})

router.afterEach((to, from) => {
  // store.dispatch('getWxConfig').then(data => {
  //   wxSetConfig(data)
  // })
})

export default router
